package com.itobase.questionnaire.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.itobase.questionnaire.VO.*;
import com.itobase.questionnaire.model.EnumList.QuestionTypes;
import com.itobase.questionnaire.model.EnumList.States;
import com.itobase.questionnaire.model.*;
import com.itobase.questionnaire.model.auth.User;
import com.itobase.questionnaire.repository.*;
import com.itobase.questionnaire.service.IOutcomeService;
import com.itobase.questionnaire.service.ISubmitService;
import com.itobase.questionnaire.service.IUserService;
import com.itobase.questionnaire.template.Constant;
import com.itobase.questionnaire.util.*;
import com.itobase.questionnaire.util.DateUtil;
import com.mongodb.client.model.ValidationLevel;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.tomcat.util.bcel.Const;
import org.apache.xmlbeans.impl.xb.xsdschema.All;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;

/**
 * @author cong
 * @date 2018/7/29
 */
@Service
public class SubmitService implements ISubmitService {

    @Autowired
    SubmitRepository submitRepository;

    @Autowired
    SurveyRepository surveyRepository;

    @Autowired
    UserRepository userRepository;

    @Autowired
    QuesnaireRepository quesnaireRepository;

    @Autowired
    IUserService userService;

    @Autowired
    SectionRateRepository sectionRateRepository;

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    SurveyGroupRepository surveyGroupRepository;

    @Autowired
    exUserRepository exUserRepository;

    @Autowired
    IOutcomeService outcomeService;

    @Override
    public Message addSubmission(Submission submission, HttpServletRequest request) throws Throwable {
        final String anonymousId =Optional.ofNullable(userRepository.findByUsername("anonymous").getId()).orElseThrow(()->new RuntimeException("请联系管理员设置默认账户"));;
        Survey survey = Optional.ofNullable(surveyRepository.findOne(submission.getSurveyId())).orElseThrow(()->new RuntimeException("该提交对应的调查不存在"));
        Map<String,String> outcome = new HashMap<>();
        if (!survey.getState().equals(States.running)) {
            return Message.createErr("该调查不处于运行时间，提交失败");
        } else {
            String uuid = getIpAddr(request).concat(getRequestBrowserInfo(request));
            if(survey.getPrivately()){
                if(submitRepository.findByUserIdAndSurveyId(AuthUtil.getUserId(),submission.getSurveyId())!=null){
                    return Message.createErr("您已经提交，请勿重复提交");
                }
                String userId = AuthUtil.getUserId();
                submission.setUserId(userId);
                User user = userRepository.findOne(userId);
                submission.setIdentity(user.getUserTypeId().equals(Constant.TEACID)?Constant.teacIdentity:Constant.stuIdentity);
                List<BaseInfo> baseInfoList = userService.getUserInfoByIds(Collections.singletonList(userId),survey.getSurveyGroupId());
                Float satisfaction = outcomeService.calculateRate(submission);
                baseInfoList.forEach(baseInfo -> {
                    if(StringUtil.isNotEmpty(baseInfo.getType())){
                        outcome.put(baseInfo.getType(),String.valueOf(satisfaction));
                    }
                });
                submission.setOutcome(outcome);
            }else{
                if(submitRepository.findByUuidAndSurveyId(uuid,submission.getSurveyId())!=null){
                    return Message.createErr("您已经提交，请勿重复提交");
                }
                submission.setUserId(anonymousId);
            }
            String now = DateUtil.format(new Date());
            Map<String, String> submitInfo = new HashMap<>();
            submitInfo.put("IP", getIpAddr(request));
            submitInfo.put("Browser", getRequestBrowserInfo(request));
            submission.setUuid(uuid);
            submission.setSubmitTime(now);
            submission.setSubmitInfo(submitInfo);
            String jsonSubmit = JSON.toJSONString(submitRepository.insert(submission));
            return Message.createSuc(jsonSubmit);
        }
    }





    @SuppressWarnings("unchecked")
    @Override
    public PageDatas<CompleteVO> getUserByComplete(String id, List<User> users,String criteria,Pageable pageable,String keyword) {

        Survey survey = surveyRepository.findOne(id);
        JSONObject allUserComplete = new JSONObject();
        List<User> undone = new ArrayList<>();
        List<User> done = new ArrayList<>();
        List<CompleteVO> allResult = new ArrayList<>();
        if(StringUtil.isNotEmpty(keyword)){
            users = exUserRepository.findUserByIdsAndKeyword(keyword,users.stream().map(User::getId).collect(Collectors.toList()));
        }
        users.forEach(user -> {
            if (submitRepository.findByUserIdAndSurveyId(user.getId(), id) != null) {
                done.add(user);
            } else {
                undone.add(user);
            }
        });
        List<String> userIds = new ArrayList<>();
        undone.forEach(e -> {
            if(e.getId()!=null){
                userIds.add(e.getId());
            }
        });
        if(StringUtil.isNotEmpty(criteria)){
            List<CompleteVO> unCompleteList = getCompleteVO(userIds,survey);
            List<CompleteVO> fitCompleteList = new CopyOnWriteArrayList<>();
            unCompleteList.forEach(completeVO -> {
                if(criteria.equals(completeVO.getBaseInfo().getType())){
                    completeVO.setComplete(false);
                    fitCompleteList.add(completeVO);
                }
            });
            allResult.addAll(fitCompleteList);
            userIds.clear();
            List<CompleteVO> fitCompleteList2 = new CopyOnWriteArrayList<>();
            done.forEach(e -> userIds.add(e.getId()));
            List<CompleteVO> completeList = getCompleteVO(userIds,survey);
            completeList.forEach(completeVO -> {
                if(criteria.equals(completeVO.getBaseInfo().getType())){
                    completeVO.setComplete(true);
                    fitCompleteList2.add(completeVO);
                }
            });
            allResult.addAll(fitCompleteList2);
        }else{
            allResult.addAll(getCompleteVO(userIds,survey).stream().peek(e-> e.setComplete(false)).collect(Collectors.toList()));
            userIds.clear();

            done.forEach(e -> userIds.add(e.getId()));
            allResult.addAll(getCompleteVO(userIds,survey).stream().peek(e-> e.setComplete(true)).collect(Collectors.toList()));
        }
        Collections.sort(allResult);
        return PagingUtils.paging(pageable.getPageNumber(),allResult,pageable.getPageSize());
    }

    @SuppressWarnings("unchecked")
    @Override
    public CountCompleteType getTypeCompleteCount(Survey survey) {
        List<User> userList = survey.getUserList();
        /*
        故意构造超出范围的pageable来获取所有的数据；
         */
        Pageable pageable = new PageRequest(userList.size(),userList.size());
        List<CompleteVO> completeVOList = getUserByComplete(survey.getId(),userList,null,pageable,null).getDatas();
        CountCompleteType countCompleteType = new CountCompleteType();
        String surveyGroupId = Optional.of(survey.getSurveyGroupId()).orElseThrow(()->new RuntimeException("未绑定调查组"));
        SurveyGroup surveyGroup = surveyGroupRepository.findOne(surveyGroupId);
        countCompleteType.setGroupName(surveyGroup.getGroupName());
        Map<String,Integer> typeCountMap = new HashMap<>();
        String type;
        for (CompleteVO completeVO : completeVOList) {
            if(!completeVO.getComplete()){
                type = completeVO.getBaseInfo().getType();
                if(!StringUtil.isNotEmpty(type)) continue;
                if (!typeCountMap.containsKey(completeVO.getBaseInfo().getType())) {
                    typeCountMap.put(type,1);
                }else{
                    Integer count = typeCountMap.get(type);
                    typeCountMap.put(type,++count);
                }
            }
        }
        for(String singleType:surveyGroup.getGroup().keySet()){
            if(!typeCountMap.containsKey(singleType)){
                typeCountMap.put(singleType,0);
            }
        }
        countCompleteType.setTypeCount(typeCountMap);
        return countCompleteType;
    }

    @Override
    public Integer getSubmitsCount(String surveyId) {
        List<Submission> submissionList = submitRepository.findBySurveyId(surveyId);
        int size = 0;
        for (Submission submission : submissionList) {
            size += submission.getOutcome().size();
        }
        return size;
    }

    private List<CompleteVO> getCompleteVO(List<String> userIds, Survey survey){
        List<BaseInfo> infoList = userService.getUserInfoByIds(userIds,survey.getSurveyGroupId());
        List<CompleteVO> completeVOList = new ArrayList<>();
        CompleteVO completeVO;
        for (BaseInfo info : infoList) {
            Submission submission = submitRepository.findByUserIdAndSurveyId(info.getId(), survey.getId());
            completeVO = new CompleteVO();
            completeVO.setBaseInfo(info);
            if(submission!=null){
                completeVO.setSubmitTime(submission.getSubmitTime());
                completeVO.setSubmitId(submission.getId());
            }
            completeVOList.add(completeVO);
        }
        return completeVOList;
    }


    /**
     * 匿名调查的人员完成情况
     * @param surveyId
     * @return
     */
    @Override
    public PageDatas<CompleteVO> getCompleteAnonymous(String surveyId,Pageable pageable) {
        List<Submission> submissionList = submitRepository.findBySurveyId(surveyId);
        List<CompleteVO> completeVOList = new ArrayList<>();
        CompleteVO completeVO;
        for (Submission e : submissionList) {
            completeVO = new CompleteVO();
            completeVO.setSubmitTime(e.getSubmitTime());
            completeVO.setSubmitId(e.getId());
            completeVO.setComplete(true);
            completeVOList.add(completeVO);
        }
        PageDatas<CompleteVO> pageDatas = PagingUtils.paging(pageable.getPageNumber(),completeVOList,pageable.getPageSize());
        return pageDatas;
    }

    @Override
    public Integer getResultExcel(String id, HttpServletResponse response) {
        final Integer unRelatedInfoNum = 2;//前两列是和题目无关的信息
        Survey survey = surveyRepository.findOne(id);
        Questionnaire questionnaire = quesnaireRepository.findOne(survey.getQuestionsID());
        List<Question> questionList = questionnaire.getQuestionList();//所有的headName
        List<Submission> submissionList = submitRepository.findBySurveyId(id);

        String excelTitle = survey.getTitle();

        HSSFWorkbook wb = new HSSFWorkbook();

        HSSFCellStyle columnTopStyle = outcomeService.getColumnTopStyle(wb);//获取列头样式对象
        HSSFCellStyle dataStyle = outcomeService.getStyle(wb);
        String sheetName = "";
        if(!StringUtil.isNotEmpty(questionnaire.getName())){
            sheetName="未命名";
        }else{
            sheetName=questionnaire.getName();
        }
        HSSFSheet sheet = wb.createSheet(sheetName);
        sheet.setDefaultColumnWidth(30);
        HSSFRow row0 = sheet.createRow(0);
        HSSFCell cellTitle = row0.createCell(0);
        sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, questionList.size() + unRelatedInfoNum));
        cellTitle.setCellValue(excelTitle + "答卷详情");

        cellTitle.setCellStyle(columnTopStyle);


        int colNum = questionList.size() + unRelatedInfoNum; //第一列为填写人username,第二列：人员类型

        HSSFRow rowHeadName = sheet.createRow(2);//第0行和第一行为标题

        /**
         * 创建表头
         */
        for (int n = 0; n < colNum; n++) {
            HSSFCell cellRowName = rowHeadName.createCell(n);
            cellRowName.setCellType(CellType.STRING);
            if (n == 0) {
                cellRowName.setCellValue("学号/工号");
                cellRowName.setCellStyle(columnTopStyle);
                continue;
            }else if(n==1){
                cellRowName.setCellValue("类型");
                cellRowName.setCellStyle(columnTopStyle);
                continue;
            }
            Question question = questionList.get(n - unRelatedInfoNum);
            StringBuilder head = new StringBuilder(question.getIssue());
            QuestionTypes type = question.getType();
            if (type.equals(QuestionTypes.Single) || type.equals(QuestionTypes.Multiple)) {
                question.getOptions().forEach(e -> head.append("\r\n").append(e));
            }
            HSSFRichTextString text = new HSSFRichTextString(head.toString());
            System.out.println(head.toString()); //test
            cellRowName.setCellValue(text);
            cellRowName.setCellStyle(columnTopStyle);
        }


        /**
         * 将数据导入excel
         */
        User user;
        int rowIndex = 3;//前三行是标题和表头
        for (int i = 0; i < submissionList.size(); i++,rowIndex++) {


            Submission submission = submissionList.get(i);
            Set<String> types = submission.getOutcome().keySet();
            Map<Integer, String> answer = submission.getAnswer();
            user = userRepository.findOne(submission.getUserId());
            HSSFRow row = sheet.createRow(rowIndex);//前三行是标题和表头

            for(String type:types){
                for (int col = 0; col < colNum; col++) {
                    HSSFCell cell = row.createCell(col, CellType.STRING);
                    if (col == 0) {
                        if(user.getUsername().equals("anonymous")){
                            cell.setCellValue("匿名调查");
                        }else{
                            cell.setCellValue(user.getUsername());
                        }
                    } else if (col ==1){
                        cell.setCellValue(type);
                    }else {
                        Question question = questionList.get(col-unRelatedInfoNum);
                        int temp = col-1;//根据题号拿题目的答案，题号从1开始
                        if(temp>=4) temp--;
                        String value = answer.get(temp);
                        if(StringUtil.isNotEmpty(value)){
                            if(!question.getType().equals(QuestionTypes.Blanks)&&value.contains(".")){

                                value = value.substring(0,value.indexOf("."));
                            }
                        }else{
                            value="";
                        }
                        if(user.getUserTypeId().equals(Constant.TEACID)&&col==Constant.stuNum){
                            cell.setCellValue("");
                            cell.setCellStyle(dataStyle);
                            continue;
                        }
                        if((user.getUserTypeId().equals(Constant.STUID)||user.getUserTypeId().equals(Constant.GRADUATE_STUDENT_ID))&&col== Constant.teacNum) {
                            cell.setCellValue("");
                            cell.setCellStyle(dataStyle);
                            continue;
                        }
                        cell.setCellValue(value);
                    }
                    cell.setCellStyle(dataStyle);
                }
            }

        }
        outcomeService.writeToResponse(response, wb,survey.getTitle().concat("详细答案"));
        return submissionList.size();
    }


    /**
     * 根据自定义的问卷答案查询提交；
     *
     * @param surveyId
     * @param params
     * @return
     */
    @Override
    public JSONObject getSubmitTime(String surveyId, List<BaseParam> params) {
        List<Submission> submissionList = submitRepository.findBySurveyId(surveyId);
        JSONObject timeAndId = new JSONObject();

        submissionList.forEach(submission -> {
            Map<Integer, String> answer = submission.getAnswer();
            String realAnswer;
            boolean match = true;
            for (BaseParam param : params) {
                realAnswer = answer.get(param.getOrderNum());
                if (param.getIs() && (!realAnswer.equals(param.getValue()))) {
                    match = false;
                } else if ((!param.getIs()) && (realAnswer.equals(param.getValue()))) {
                    match = false;
                }
            }
            if (match) {
                timeAndId.put("id", submission.getId());
                timeAndId.put("submitTime", submission.getSubmitTime());
            }
        });

        return timeAndId;
    }






    @Override
    public JSONObject getStatics(String surveyId, Integer orderNum, Page<Submission> pageSubmits) {
        Survey survey = surveyRepository.findOne(surveyId);
        JSONObject jsonObject = new JSONObject();
        PageDatas<BlankResult> blankResultPageDatas = new PageDatas<>(pageSubmits.getTotalElements(),pageSubmits.getTotalPages());
        List<Submission> submissionList = pageSubmits.getContent();
        List<Question> questionList = quesnaireRepository.findOne(survey.getQuestionsID()).getQuestionList();
        QuestionTypes type = QuestionTypes.Single;
        Question question = new Question();
        for (Question e : questionList) {
            if (e.getOrderNumber().equals(orderNum)) {
                type = e.getType();
                question = e;
            }
        }
        switch (type) {
            case Single:
                //添加选择题的具体id
                List<BlankResult> blankResultList = new ArrayList<>();
                BlankResult blankResultSingle;
                for (Submission e : submissionList) {
                    if(!needJump(e,orderNum)){
                        Integer rightOrder = getOrderByIdentity(orderNum);
                        blankResultSingle = new BlankResult();
                        blankResultSingle.setAnswer(e.getAnswer().get(rightOrder));
                        blankResultSingle.setTime(e.getSubmitTime());
                        blankResultSingle.setId(e.getId());
                        blankResultList.add(blankResultSingle);
                    }
                }
                List<ResultStatistic> statistics = getPercents(surveyId,orderNum);
                blankResultPageDatas.setDatas(blankResultList);
                jsonObject.put("单选题统计结果", statistics);
                jsonObject.put("具体答案和id",blankResultPageDatas);
                jsonObject.put("选择题题目",question.getIssue());
                jsonObject.put("type","Single");
                return jsonObject;

            case Multiple:
                jsonObject.put("多选题统计结果", "不支持多选题进行统计");
                return jsonObject;
            case Blanks:
                List<BlankResult> blankList = new ArrayList<>();
                BlankResult blankResult;
                for (Submission submission : submissionList) {
                    blankResult = new BlankResult();
                    blankResult.setId(submission.getId());
                    blankResult.setTime(submission.getSubmitTime());
                    blankResult.setAnswer(submission.getAnswer().get(orderNum-1));
                    blankList.add(blankResult);
                }
                blankResultPageDatas.setDatas(blankList);
                jsonObject.put("填空题结果", blankResultPageDatas);
                jsonObject.put("填空题题目",question.getIssue());
                jsonObject.put("type","Blanks");
                return jsonObject;
        }
        return null;
    }


    private List<ResultStatistic> getPercents(String surveyId,Integer orderNum){
        List<Submission> allSubmission = submitRepository.findBySurveyId(surveyId);
        List<String> allAnswer = new ArrayList<>();
        allSubmission.forEach(submission -> {
            if(!needJump(submission,orderNum)){
                Integer rightOrder = getOrderByIdentity(orderNum);
                allAnswer.add(submission.getAnswer().get(rightOrder));
            }
        });
        DecimalFormat decimalFormat = new DecimalFormat("0.00");
        List<ResultStatistic> statistics = new ArrayList<>();
        Map<String, Integer> result = new HashMap<>();
        int total = allAnswer.size();
        Integer count;
        for (String s : allAnswer) {
            if (result.containsKey(s)) {
                count = result.get(s);
                count++;
                result.put(s, count);
            } else {
                result.put(s, 1);
            }
        }
        ResultStatistic statistic;
        for (Map.Entry<String, Integer> entry : result.entrySet()) {
            statistic = new ResultStatistic();
            statistic.setAnswer(entry.getKey());
            statistic.setCount(entry.getValue());
            statistic.setPercents(decimalFormat.format((entry.getValue()*1.00) / total*100).concat("%"));

            statistics.add(statistic);
        }
        return statistics ;
    }

    private Integer getOrderByIdentity(Integer orderNum){
        if(orderNum>=4) {
            return --orderNum;
        }else{
            return orderNum;
        }
    }

    private Boolean needJump(Submission submission,Integer orderNum){
        boolean jump = false;
        //教师也没有熟悉不熟悉这一题；
        if(submission.getIdentity().equals(Constant.teacIdentity) && (orderNum.equals(Constant.stuNum)||orderNum.equals(5))){
            jump = true;
        }
        if(submission.getIdentity().equals(Constant.stuIdentity) && orderNum.equals(Constant.teacNum)){
            jump = true;
        }

        return jump;
    }



    /**
     * 获得一份调查中每个人的满意度以及总满意度
     * @param surveyId
     * @return
     */
    @Override
    public SurveyRate getSatisfaction(String surveyId, String criteria,
                                      @PageableDefault(sort = "submitTIme",direction = Sort.Direction.DESC)Pageable pageable,
                                      String keyword) {

        List<UserInfo> userInfos = new ArrayList<>();
        Survey survey = Optional.ofNullable(surveyRepository.findOne(surveyId)).orElseThrow(()->new RuntimeException("调查id错误"));
        String surveyGroupId = Optional.ofNullable(survey.getSurveyGroupId()).orElseThrow(()->new RuntimeException("调查未绑定调查组"));
        List<String> userIds = new ArrayList<>();
        /*
        只返回已经提交的人的满意度以及信息。
         */
        //survey.getUserList().forEach(e->userIds.add(e.getId()));
        Page<Submission> pageSubmits = submitRepository.findBySurveyId(surveyId,new PageRequest(pageable.getPageNumber()-1,pageable.getPageSize(),pageable.getSort()));
        List<Submission> submissionList = pageSubmits.getContent();
        submissionList.forEach(submission->{
            for(int i=0;i<submission.getOutcome().size();i++){
                userIds.add(submission.getUserId());
            }
        });

        if(StringUtil.isNotEmpty(keyword)){
            List<User> userList = exUserRepository.findUserByIdsAndKeyword(keyword,userIds);
            userIds.clear();
            userList.forEach(e->userIds.add(e.getId()));
        }

        List<BaseInfo> baseInfos = userService.getUserInfoByIds(userIds,surveyGroupId);
        if(StringUtil.isNotEmpty(criteria)){
            List<BaseInfo> fitBaseInfo = new ArrayList<>();
            for (BaseInfo baseInfo : baseInfos) {
                if(criteria.equals(baseInfo.getType())){
                    fitBaseInfo.add(baseInfo);
                }
            }
            baseInfos = fitBaseInfo;
        }

        UserInfo userInfo;
        for (BaseInfo baseInfo : baseInfos) {
            userInfo = new UserInfo();
            userInfo.setBaseInfo(baseInfo);
            Submission submission = submitRepository.findByUserIdAndSurveyId(baseInfo.getId(),surveyId);
            if(submission!=null){
                userInfo.setSubmitId(submission.getId());
                userInfo.setSatisfaction(Float.valueOf(submission.getOutcome().get(baseInfo.getType())));
            }
            userInfos.add(userInfo);
        }

        SurveyRate surveyRate = new SurveyRate();
        surveyRate.setUserInfoList(new PageDatas<>(pageSubmits.getTotalElements(), pageSubmits.getTotalPages(), userInfos));
        survey.setContentRate(outcomeService.getSurveyContentRate(survey));
        surveyRepository.save(survey);
        surveyRate.setTotalRate(Float.valueOf(survey.getContentRate()));
        return surveyRate;
    }


    private Set<String> getTeacherIds(List<Submission> submissionList){
        Set<String> teacherIds = new HashSet<>();
        List<String> allIds = new ArrayList<>();
        submissionList.forEach(e->allIds.add(e.getUserId()));
        List<User> userList = userRepository.findByIdIn(allIds.toArray(new String[0]));
        userList.forEach(user->{
            if(user.getUserTypeId().equals(Constant.TEACID)){
                teacherIds.add(user.getId());
            }
        });
        return teacherIds;
    }



    /**
     * 获取ip
     *
     * @param request
     * @return
     */
    private static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("X-Real-IP");
        if (ip != null && !"".equals(ip) && !"unknown".equalsIgnoreCase(ip)) {
            return ip;
        }
        ip = request.getHeader("X-Forwarded-For");
        if (ip != null && !"".equals(ip) && !"unknown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个IP值，第一个为真实IP。
            int index = ip.indexOf(',');
            if (index != -1) {
                return ip.substring(0, index);
            } else {
                return ip;
            }
        } else {
            return request.getRemoteAddr();
        }
    }

    /**
     * 获取来访者的浏览器版本
     *
     * @param request
     * @return
     */
    private static String getRequestBrowserInfo(HttpServletRequest request) {
        String browserVersion = "";
        String header = request.getHeader("user-agent");
        if (header == null || header.equals("")) {
            return "";
        }
        if (header.indexOf("MSIE") > 0) {
            browserVersion = "IE";
        } else if (header.indexOf("Firefox") > 0) {
            browserVersion = "Firefox";
        } else if (header.indexOf("Chrome") > 0) {
            browserVersion = "Chrome";
        } else if (header.indexOf("Safari") > 0) {
            browserVersion = "Safari";
        } else if (header.indexOf("Camino") > 0) {
            browserVersion = "Camino";
        } else if (header.indexOf("Konqueror") > 0) {
            browserVersion = "Konqueror";
        }
        return browserVersion;
    }

}
